package com.iams.manage.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.iams.elasticsearch.domain.ElasticsearchArchive;
import com.iams.manage.service.IElasticsearchArchiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ElasticsearchArchiveServiceImpl implements IElasticsearchArchiveService {

    private final ElasticsearchClient client;

    @Autowired
    public ElasticsearchArchiveServiceImpl(ElasticsearchClient client) {
        this.client = client;
    }

    @Override
    public List<ElasticsearchArchive> CombineSearch(Map<String, String> combineParams) {
        List<ElasticsearchArchive> list = new ArrayList<>();

        // 构建 BoolQuery
        BoolQuery.Builder boolQueryBuilder = new BoolQuery.Builder();


        // 处理静态条件
        if (combineParams.containsKey("MainType") && combineParams.containsKey("MainTypeValue")) {
            String logic = combineParams.getOrDefault("MainTypeLogic", "AND"); // 获取逻辑运算符
            addCondition(boolQueryBuilder, logic,
                    combineParams.get("MainType"),
                    combineParams.get("MainTypeValue"));
        }

        // 处理第二个主条件（添加逻辑处理）
        if (combineParams.containsKey("secondMainType") && combineParams.containsKey("secondMainTypeValue")) {
            String logic = combineParams.getOrDefault("secondMainTypeLogic", "AND");
            addCondition(boolQueryBuilder, logic,
                    combineParams.get("secondMainType"),
                    combineParams.get("secondMainTypeValue"));
        }
//        // 处理文档类型条件
//        if (combineParams.containsKey("DocumentType")) {
//            String[] documentTypes = combineParams.get("DocumentType").split(",");
//            for (String type : documentTypes) {
//                boolQueryBuilder.must(Query.of(q -> q
//                        .term(t -> t
//                                .field("documentType") // 假设文档类型字段为 documentType
//                                .value(type)
//                        )));
//            }
//        }

        // 处理动态条件(处理中间有空条件)
        int index = 0;
        int maxEmptyChecks = 10; // 连续空条件的最大检查次数，避免无限循环
        int emptyCount = 0;

        while (emptyCount < maxEmptyChecks) {
            String fieldKey = "dynamicField" + index;
            String valueKey = "dynamicValue" + index;
            String logicKey = "dynamicLogic" + index; // 新增逻辑参数
            String field = combineParams.getOrDefault(fieldKey, "");
            String value = combineParams.getOrDefault(valueKey, "");
            String logic = combineParams.getOrDefault(logicKey, "AND"); // 获取动态逻辑

            if (!field.isEmpty() && !value.isEmpty()) {
                addCondition(boolQueryBuilder, logic, field, value); // 统一处理条件
                emptyCount = 0;
            } else {
                emptyCount++;
            }
            index++;
        };

////                // 根据字段名动态处理查询条件
//////            boolQueryBuilder.must(Query.of(q -> q
//////                    .match(MatchQuery.of(m -> m
//////                            .field(key) // 动态使用字段名
//////                            .query(value) // 使用条件的值
//////                    ))
//////            ));
//
//
//            }
//
//        });

        try {
            SearchResponse<ElasticsearchArchive> response = client.search(s -> s
                            .index("archives")
                            .query(q -> q.bool(boolQueryBuilder.build())),
                    ElasticsearchArchive.class
            );

            for (Hit<ElasticsearchArchive> hit : response.hits().hits()) {
                if (hit.source() != null) {
                    list.add(hit.source());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("执行 Elasticsearch 查询失败", e);
        }

        return list;
    }
    // 新增条件处理方法（保持原有字段类型判断）
    private void addCondition(BoolQuery.Builder builder, String logic, String field, String value) {
        if (field == null || value == null || field.isEmpty() || value.isEmpty()) return;

        // 保持原有字段类型判断
        final Query query;
        if (field.equals("filePath") || field.equals("mysqlDanghao")) {
            query = Query.of(q -> q.term(t -> t.field(field).value(value)));
        } else {
            query = Query.of(q -> q.match(m -> m.field(field).query(value)));
        }

        // 添加逻辑判断
        switch (logic.toUpperCase()) {
            case "OR":
                builder.should(query);
                break;
            case "NOT":
                builder.mustNot(query);
                break;
            case "AND":
            default:
                builder.must(query);
                break;
        }
    }
}
